<template>
  <div>
    <div v-if="userrole == 2">
      <el-row :gutter="20">
        <el-col :span="1" :offset="3">
          <el-button type="primary" @click="back" icon="el-icon-arrow-left"
            >返回</el-button
          >
        </el-col>
        <el-col :span="16">
          <div class="center">
            <h3>编辑心理知识</h3>
          </div>
          <div class="center">
            <el-form
              :model="articleForm"
              label-width="80px"
              style="width: 100%; height: 80vh"
            >
              <el-form-item label="文章标题">
                <el-input
                  v-model="articleForm.title"
                  placeholder="请输入文章标题"
                ></el-input>
              </el-form-item>
              <el-form-item label="文件简介">
                <el-input
                  v-model="articleForm.brief"
                  placeholder="请输入文章简介"
                ></el-input>
              </el-form-item>
              <el-form-item label="是否轮播">
                <el-switch
                  v-model="flag"
                  active-color="#13ce66"
                  inactive-color="#ff4949"
                >
                </el-switch>
              </el-form-item>
              <el-form-item label="上传封面">
                <el-upload
                  class="upload-demo"
                  action="/api/oss/uploadCover"
                  :limit="1"
                  :on-exceed="handleExceed"
                  :on-success="handleSuccess"
                  :file-list="fileList"
                  list-type="picture"
                >
                  <el-button size="small" type="primary">点击上传</el-button>
                </el-upload>
              </el-form-item>
              <el-form-item label="编辑内容">
                <!-- <el-button
                  type="primary"
                  size="small"
                  @click="handleInsertImage"
                  >插入图片</el-button
                > -->
                <el-upload
                  class="upload-demo"
                  action="/api/oss/uploadContentImg"
                  :on-success="updateSuccess"
                  :file-list="contentImgs"
                  list-type="picture"
                  :show-file-list="false"
                >
                  <el-button
                    size="small"
                    type="primary"
                    :disabled="isUploadDisabled"
                    >插入图片</el-button
                  >
                </el-upload>
              </el-form-item>
              <el-form-item>
                <!-- 自定义富文本编辑器 -->
                <div
                  class="custom-editor"
                  contenteditable="true"
                  ref="editor"
                  @input="handleInput"
                  @blur="handleBlur"
                  @focus="isUploadDisabled = false"
                ></div>
              </el-form-item>
              <el-form-item style="padding-top: 0vh">
                <el-button type="primary" @click="submitArticle"
                  >发布文章</el-button
                >
              </el-form-item>
            </el-form>
          </div>
        </el-col>
      </el-row>
    </div>
    <div v-else class="center">
      <div>请先登录咨询师账号~</div>
    </div>
  </div>
</template>

<script>
export default {
  components: {},
  data() {
    return {
      flag: false,
      articleForm: {
        title: "", //标题
        brief: "", //简介
        cover: "", //封面
      },
      fileList: [], //封面
      contentImgs: [], //内容图片
      editorContent: "", // 富文本编辑器内容
      isUploadDisabled: true, //上传禁用
    };
  },
  computed: {
    userrole() {
      return localStorage.getItem("userrole");
    }, //是否轮播
    iscarousel() {
      return this.flag ? 1 : 0;
    },
  },
  methods: {
    handleBlur() {
      setTimeout(() => {
        this.isUploadDisabled = true;
      }, 200); // 1000毫秒等于1秒
    },
    handleExceed(files, fileList) {
      this.$message.warning(`只能上传一张封面图片，请先删除已添加的封面图片`);
    },
    handleSuccess(response, file, fileList) {
      let pre = this.$store.getters.getCoverPre;
      let cover = pre + response.fileName;
      console.log(cover);
      this.articleForm.cover = cover;
      this.fileList = fileList.slice(-1); // 只保留最新上传的图片
      this.$message.success("上传成功");
    },
    updateSuccess(response, file, fileList) {
      let pre = this.$store.getters.getContentImg;
      let img = pre + response.fileName;
      console.log(img);
      this.handleInsertImage(img);
    },
    submitArticle() {
      if (!this.checkFormNotEmpty()) {
        return;
      }
      // 提交文章的逻辑，可以将文章标题和内容发送到后端保存
      console.log("提交文章：", this.articleForm);
      // 在这里可以添加发送文章数据到后端的代码
      this.$request.postHttp({
        url: "/knowledge/addKnowledge",
        data: {
          authorid: localStorage.getItem("userId"),
          title: this.articleForm.title,
          brief: this.articleForm.brief,
          content: this.editorContent,
          iscarousel: this.iscarousel,
          cover: this.articleForm.cover,
        },
        success: (data) => {
          console.log(data.data);
          if (data.code == 200) {
            this.$message.success("发布成功！");
            this.$router.back();
          }
        },
        error: (error) => {
          console.log(data.data);
        },
      });
    },
    handleInput(event) {
      this.editorContent = event.target.innerHTML;
    },
    handleInsertImage(img) {
      // 在这里执行插入图片的操作，可以弹出图片上传对话框或其他操作
      // 这里仅示例在编辑器中插入一个固定的图片链接
      // 检查光标位置是否在富文本编辑器内
      const editor = this.$refs.editor;
      const selection = window.getSelection();
      if (editor.contains(selection.anchorNode)) {
        // 在这里执行插入图片的操作，可以弹出图片上传对话框或其他操作
        // 这里仅示例在编辑器中插入一个固定的图片链接
        const imageUrl = img; // 示例图片链接
        const imgTag = `<div style="display: flex; align-items: center; justify-content: center;"><img src="${imageUrl}" alt="Inserted Image" style="max-width: 100%; max-height: 400px;"></div></br>`; // 设置图片最大宽度和最大高度
        this.insertAtCursor(imgTag);
      } else {
      }
    },
    insertAtCursor(html) {
      const range = window.getSelection().getRangeAt(0);
      range.deleteContents();
      const frag = range.createContextualFragment(html);
      range.insertNode(frag);
    },
    checkFormNotEmpty() {
      if (!this.articleForm.title) {
        this.$message.error("文章标题不能为空");
        return false;
      }
      if (!this.articleForm.brief) {
        this.$message.error("文件简介不能为空");
        return false;
      }
      if (!this.articleForm.cover) {
        this.$message.error("请上传封面");
        return false;
      }
      if (!this.editorContent.trim()) {
        this.$message.error("编辑内容不能为空");
        return false;
      }
      return true;
    },
    back() {
      this.$router.back();
    },
  },
};
</script>

<style scoped>
.center {
  display: flex;
  justify-content: center;
}

.custom-editor {
  border: 1px solid #ccc;
  min-height: 400px;
  padding: 10px;
  overflow-y: auto;
}
</style>
